using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text;
using UnityEditor.ProjectWindowCallback;
using System.Text.RegularExpressions;

namespace FShaderInspector
{
    public abstract class FShaderGUIEditor
    {
        /// <summary> Shader模版路径</summary>
        public const string ShaderTemplatePath = "CREATE_URP_SHADER_PATH";

        [MenuItem("Assets/Create/Shader/Fast Shader/Unlit Shader", false, 83)]
        public static void CreatURPShaderTemplate()
        {
            var shaderPath = GetShaderPath("UnlitURPShader");
            ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<ShaderAsset>(), GetSelectPathOrFallback() + "/NewUnlitShader.shader", null, shaderPath);
        }

        [MenuItem("Assets/Create/Shader/Fast Shader/Unlit Shader (Simple)", false, 83)]
        public static void CreatSimpleUnlitShaderTemplate()
        {
            var shaderPath = GetShaderPath("SimpleUnlitShader");
            ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<ShaderAsset>(), GetSelectPathOrFallback() + "/SimpleUnlitShader.shader", null, shaderPath);
        }

        /// <summary> 获取Root路径 </summary>
        /// <returns>路径</returns>
        static string GetRootPath()
        {
            var guid = AssetDatabase.FindAssets("FShaderGUI.Editor")?[0];
            var fullPath = AssetDatabase.GUIDToAssetPath(guid);
            return fullPath.Replace("/Editor/FShaderGUI/FShaderGUI.Editor.cs", "");
        }

        /// <summary> 获取Shader文件目录 </summary>
        /// <returns>Shader路径</returns>
        static string GetShaderPath(string shaderName)
        {
            var path = EditorPrefs.GetString(ShaderTemplatePath);

            if (File.Exists(path) && path.EndsWith($"{shaderName}.txt")) return path;

            path = $"{GetRootPath()}/Editor/{shaderName}.txt";
            EditorPrefs.SetString(ShaderTemplatePath, path);
            return path;
        }

        /// <summary> 获取选择的路径 </summary>
        /// <returns>路径</returns>
        static string GetSelectPathOrFallback()
        {
            var path = "Assets";
            foreach (Object obj in Selection.GetFiltered(typeof(Object), SelectionMode.Assets))
            {
                path = AssetDatabase.GetAssetPath(obj);
                if (string.IsNullOrEmpty(path) || !File.Exists(path)) continue;
                path = Path.GetDirectoryName(path);
                break;
            }

            return path;
        }
    }

    /// <summary> Shader资产 </summary>
    public class ShaderAsset : EndNameEditAction
    {
        public override void Action(int instanceId, string pathName, string resourceFile)
        {
            var o = CreateScriptAssetFromTemplate(pathName, resourceFile);
            ProjectWindowUtil.ShowCreatedAsset(o);
        }

        static Object CreateScriptAssetFromTemplate(string pathName, string resourceFile)
        {
            var fullPath = Path.GetFullPath(pathName);
            var streamReader = new StreamReader(resourceFile);
            //读取模板内容
            var text = streamReader.ReadToEnd();
            streamReader.Close();
            var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(pathName);

            //将模板的#NAME# 替换成文件名
            text = Regex.Replace(text, "#NAME#", fileNameWithoutExtension);

            // 写入文件 并导入资源
            var encoding = new UTF8Encoding(true, false);
            var streamWriter = new StreamWriter(fullPath, false, encoding);
            streamWriter.Write(text);
            streamWriter.Close();
            AssetDatabase.ImportAsset(pathName);
            return AssetDatabase.LoadAssetAtPath(pathName, typeof(Object));
        }
    }
}